package cn.throwx.sc.ch1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @author throwable
 * @version v1
 * @description
 * @since 2021/10/26 0:52
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 允许匿名访问"/"和"/home"
                .antMatchers("/", "/home").permitAll()
                // 其他任意请求必须要进行认证
                .anyRequest().authenticated()
                .and()
                // 允许匿名访问"/login"
                .formLogin().loginPage("/login").permitAll()
                .and()
                // 允许匿名访问"/logout"
                .logout().permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        // withDefaultPasswordEncoder是不安全的,不建议使用
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("throwx")
                .password("throwable")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }
}
